/*
 * @Description: 城市选择器
 * @Author: iamsmiling
 * @Date: 2021-05-30 19:47:31
 * @LastEditTime: 2021-05-30 21:04:56
 */

import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

Future<AddressEntity?> showCityPicker(BuildContext context,
    {AddressEntity? address}) async {
  Map json = jsonDecode(await rootBundle.loadString("assets/data/china.json"));
  List<Map> cityList = (json["city"] as List).cast<Map>();
  List<Map> provinceList = (json["province"] as List).cast<Map>();
  return showModalBottomSheet<AddressEntity?>(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10),
          topRight: Radius.circular(10),
        ),
      ),
      builder: (BuildContext context) {
        return Material(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(10),
                topRight: Radius.circular(10),
              ),
            ),
            child: Container(
              height: MediaQuery.of(context).size.height * 238 / 675,
              child: _CityPickerModal(
                cityList: cityList,
                proviceList: provinceList,
              ),
            ));
      });
}

class AddressEntity {
  late String province;
  late int? provinceId;
  late String city;
  late int? cityId;

  AddressEntity.fromName(
      {required String provinceName, required String cityName}) {
    province = provinceName;
    city = cityName;
  }

  AddressEntity.fromId({required int provinceId, required int cityId}) {
    this.provinceId = provinceId;
    this.cityId = cityId;
  }

  AddressEntity();
}

class _CityPickerModal extends StatefulWidget {
  final List<Map> proviceList;
  final List<Map> cityList;
  final AddressEntity? address;
  _CityPickerModal(
      {Key? key,
      required this.proviceList,
      required this.cityList,
      this.address})
      : super(key: key);

  @override
  __CityPickerModalState createState() => __CityPickerModalState();
}

class __CityPickerModalState extends State<_CityPickerModal> {
  late List<Map> proviceList;

  late List<Map> cityList;

  late StreamController<List<Map>> _controller;

  late AddressEntity address;
  @override
  void initState() {
    super.initState();
    proviceList = widget.proviceList;
    cityList = widget.cityList;
    address = widget.address ?? AddressEntity();
    _controller = StreamController<List<Map>>();
  }

  @override
  void dispose() {
    _controller.close();

    super.dispose();
  }

  void _onProviceChanged(int i) {
    address.province = proviceList[i]["province_name"];
    address.provinceId = proviceList[i]["province_id"];

    List<Map> list = [];
    for (Map item in cityList) {
      if (item["province_id"] == address.provinceId) {
        list.add(item);
      }
    }
    _controller.add(list);
  }

  void _onCityChanged(int i) {
    address.city = cityList[i]["city_name"];
    address.cityId = cityList[i]["city_id"];
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.only(top: 14, bottom: 16, left: 15, right: 15),
            child: Row(
              children: [
                GestureDetector(
                  onTap: Navigator.of(context).pop,
                  child: Text(
                    "取消",
                    style: TextStyle(fontSize: 14, color: Color(0xFF888888)),
                  ),
                ),
                Spacer(),
                Text(
                  "选择合作地区",
                  style: TextStyle(
                      fontSize: 15,
                      color: Color(0xFF333333),
                      fontWeight: FontWeight.w600),
                ),
                Spacer(),
                GestureDetector(
                  onTap: () => Navigator.of(context).pop(address),
                  child: Text(
                    "确定",
                    style:
                        TextStyle(fontSize: 14, color: const Color(0xFF36BA93)),
                  ),
                )
              ],
            ),
          ),
          Divider(),
          Expanded(
              child: Row(
            children: [
              Flexible(
                  child: _CityItemBuilder(
                      onSelectedItemChanged: _onProviceChanged,
                      options: proviceList,
                      optionKey: "province_name")),
              Flexible(
                  child: StreamBuilder<List<Map>>(
                      stream: _controller.stream,
                      initialData: cityList,
                      builder: (context, snapshot) {
                        return _CityItemBuilder(
                          options: snapshot.data == null ? [] : snapshot.data!,
                          optionKey: "city_name",
                          onSelectedItemChanged: _onCityChanged,
                        );
                      }))
            ],
          ))
        ],
      ),
    );
  }
}

class _CityItemBuilder extends StatefulWidget {
  final List<Map> options;
  final int? initialId;
  final String? initialName;
  final String optionKey;
  final ValueChanged<int>? onSelectedItemChanged;
  _CityItemBuilder({
    Key? key,
    required this.options,
    required this.optionKey,
    this.initialId,
    this.initialName,
    this.onSelectedItemChanged,
  }) : super(key: key);

  @override
  __CityItemBuilderState createState() => __CityItemBuilderState();
}

class __CityItemBuilderState extends State<_CityItemBuilder> {
  late FixedExtentScrollController controller;
  @override
  void initState() {
    super.initState();
    controller = FixedExtentScrollController();
    // if (widget.initialId != null) {
    //   controller = FixedExtentScrollController(
    //     initialItem: widget.options.f
    //   );
    // }
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      child: SizedBox.expand(
          child: CupertinoPicker.builder(
        scrollController: controller,
        itemExtent: 44,
        childCount: widget.options.length,
        itemBuilder: (BuildContext context, int i) {
          return Center(
            child: Text(
              widget.options[i][widget.optionKey],
              style: TextStyle(fontSize: 15),
            ),
          );
        },
        onSelectedItemChanged: widget.onSelectedItemChanged,
      )),
    );
  }
}
